#include "course.h"
#include "fileops.h"
#include <stdio.h>
#include <string.h>

static Course courses[MAX_COURSES];
static int numCourses = 0;

void listCourses() {
    readCoursesFromFile(courses, &numCourses);
    printf("课程编号 课程名称 教师名称 上课时间 上课地点\n");
    for (int i = 0; i < numCourses; i++) {
        printf("%s %s %s %s %s\n",
               courses[i].courseID, courses[i].courseName,
               courses[i].teacherName, courses[i].courseTime,
               courses[i].courseLocation);
    }
}

void addCourse() {
    printf("请输入课程编号：");
    scanf("%s", courses[numCourses].courseID);
    printf("请输入课程名称：");
    scanf("%s", courses[numCourses].courseName);
    printf("请输入教师名称：");
    scanf("%s", courses[numCourses].teacherName);
    printf("请输入上课时间：");
    scanf("%s", courses[numCourses].courseTime);
    printf("请输入上课地点：");
    scanf("%s", courses[numCourses].courseLocation);

    numCourses++;
    saveCoursesToFile(courses, numCourses);
    printf("课程已添加成功！\n");
}

void deleteCourse() {
    char id[MAX_LENGTH];
    printf("请输入要删除的课程编号：");
    scanf("%s", id);

    int index = -1;
    for (int i = 0; i < numCourses; i++) {
        if (strcmp(courses[i].courseID, id) == 0) {
            index = i;
            break;
        }
    }

    if (index == -1) {
        printf("找不到该课程！\n");
        return;
    }

    for (int i = index; i < numCourses - 1; i++) {
        courses[i] = courses[i + 1];
    }
    numCourses--;
    saveCoursesToFile(courses, numCourses);
    printf("课程已删除成功！\n");
}

void searchCourse() {
    char name[MAX_LENGTH];
    printf("请输入要搜索的课程名称：");
    scanf("%s", name);

    int found = 0;
    for (int i = 0; i < numCourses; i++) {
        if (strstr(courses[i].courseName, name)) {
            printf("%s %s %s %s %s\n",
                   courses[i].courseID, courses[i].courseName,
                   courses[i].teacherName, courses[i].courseTime,
                   courses[i].courseLocation);
            found = 1;
        }
    }

    if (!found) {
        printf("找不到相关课程！\n");
    }
}

void updateCourse() {
    char id[MAX_LENGTH];
    printf("请输入要修改的课程编号：");
    scanf("%s", id);

    int index = -1;
    for (int i = 0; i < numCourses; i++) {
        if (strcmp(courses[i].courseID, id) == 0) {
            index = i;
            break;
        }
    }

    if (index == -1) {
        printf("找不到该课程！\n");
        return;
    }

    printf("请输入新的课程名称：");
    scanf("%s", courses[index].courseName);
    printf("请输入新的教师名称：");
    scanf("%s", courses[index].teacherName);
    printf("请输入新的上课时间：");
    scanf("%s", courses[index].courseTime);
    printf("请输入新的上课地点：");
    scanf("%s", courses[index].courseLocation);

    saveCoursesToFile(courses, numCourses);
    printf("课程信息已更新成功！\n");
}
